from flask import Flask, render_template, request, jsonify, send_file
import requests
import os
import zipfile
import hashlib
from urllib.parse import quote
import threading
import time
from datetime import datetime

app = Flask(__name__)

# 配置
DOWNLOAD_DIR = 'downloads'
STATIC_IMAGES_DIR = 'static/images'
MAX_IMAGES = 50  # 最大下载图片数量

# 全局变量存储下载状态
download_status = {
    'is_running': False,
    'current_keyword': '',
    'downloaded': 0,
    'total': 0,
    'images': []
}

def get_image_hash(image_data):
    """计算图片的哈希值用于去重"""
    return hashlib.md5(image_data).hexdigest()

def download_image(url, keyword, index):
    """下载单张图片"""
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        }
        response = requests.get(url, headers=headers, timeout=10)
        if response.status_code == 200:
            # 生成文件名
            ext = url.split('.')[-1].lower()
            if ext not in ['jpg', 'jpeg', 'png', 'gif', 'webp']:
                ext = 'jpg'
            filename = f"{keyword}_{index}.{ext}"
            filepath = os.path.join(STATIC_IMAGES_DIR, filename)
            
            # 检查是否已存在相同图片
            image_hash = get_image_hash(response.content)
            for img in download_status['images']:
                if img['hash'] == image_hash:
                    return None
            
            # 保存图片
            with open(filepath, 'wb') as f:
                f.write(response.content)
            
            return {
                'filename': filename,
                'url': url,
                'hash': image_hash,
                'path': filepath
            }
    except Exception as e:
        print(f"下载图片失败: {url}, 错误: {str(e)}")
    return None

def search_images(keyword, page=1):
    """搜索图片（使用Bing图片搜索API模拟）"""
    # 这里使用Bing图片搜索的模拟实现
    # 实际项目中可以使用Bing Search API或其他图片API
    search_url = f"https://www.bing.com/images/search"
   